package com.wosiliujing.learning.aspect;

import com.wosiliujing.learning.annotation.DynamicDataSource;
import com.wosiliujing.learning.support.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author 刘靖
 * @date 2019-11-01 14:31
 */
@Slf4j
@Aspect
@Component
public class DynamicDataSourceAspect {

    @Pointcut("@annotation(com.wosiliujing.learning.annotation.DynamicDataSource)" +
                " ||@within(com.wosiliujing.learning.annotation.DynamicDataSource)")
    public void dynamicDataSourcePointCut(){

    }


    @Around("dynamicDataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable{
        MethodSignature signature = (MethodSignature) point.getSignature();
        Class targetClass = point.getTarget().getClass();
        Method method = signature.getMethod();
        DynamicDataSource targetDataSource = (DynamicDataSource)targetClass.getAnnotation(DynamicDataSource.class);
        DynamicDataSource methodDataSource = method.getAnnotation(DynamicDataSource.class);
        if(targetDataSource != null || methodDataSource != null){
            String value;
            if(methodDataSource != null){
                value = methodDataSource.value();
            }else {
                value = targetDataSource.value();
            }

            DynamicDataSourceContextHolder.setDataSourceType(value);
            log.debug("set datasource is {}", value);
        }
        try {
            return point.proceed();
        }finally {
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }
}
